<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="chargeStationId">
        <el-input
          v-model="queryParams.chargeStationId"
          placeholder="请输入场站ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="lastUpdateTime">
        <el-input
          v-model="queryParams.lastUpdateTime"
          placeholder="请输入最后更新人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="platformAgentId">
        <!--        <el-input
                  v-model="queryParams.platformAgentId"
                  placeholder="请输入代理商ID"
                  clearable
                  @keyup.enter.native="handleQuery"
                />-->
        <el-select
          v-model="queryParams.platformAgentId"
          placeholder="代理商名称"
          clearable
          size="small">
          <el-option
            v-for="area in agentList"
            :key="area.id"
            :label="area.agentName"
            :value="area.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="shareRatio">
        <el-input
          v-model="queryParams.shareRatio"
          placeholder="请输入代理商分润比例"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:platformShare:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:platformShare:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:platformShare:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:platformShare:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="platformShareList" @selection-change="handleSelectionChange" highlight-current-row>
<!--      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />-->
      <el-table-column label="场站" align="center" prop="stationName"/>
<!--      <el-table-column label="最后更新人" align="center" prop="lastUpdateTime" />-->
      <el-table-column label="代理商" align="center" prop="platformAgentName"/>
      <el-table-column label="代理商分润比例" align="center" prop="shareRatio">
        <template slot-scope="scope">
          <el-tag
            effect="plain">
            {{ scope.row.shareRatio }}%
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="分润类别" align="center" prop="shareType">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.shareType =='profit'?'':'success'"
            effect="dark">
            {{ getLabelByValue(shareTypeList, scope.row.shareType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status"/>
      <el-table-column label="分账开关" align="center" prop="isSharing" width="100">
        <template slot-scope="scope">
          <el-switch
            style="display: block"
            v-model="scope.row.isSharing"
            @click.native.prevent="updateManager(scope.row,'isSharing')"
            disabled
            :active-value="'1'"
            :inactive-value="'0'">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="自动开关" align="center" prop="isAuto" width="100">
        <template slot-scope="scope">
          <el-switch
            style="display: block"
            v-model="scope.row.isAuto"
            @click.native.prevent="updateManager(scope.row,'isAuto')"
            disabled
            :active-value="'1'"
            :inactive-value="'0'">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            :class="['text-button', { 'active': active===scope.$index + 'handleUpdate' }]"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row),active=scope.$index + 'handleUpdate'"
            v-hasPermi="['business:platformShare:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:platformShare:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改代理商分账润规则对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="代理商" prop="platformAgentId">
          <!--          <el-input v-model="form.platformAgentId" placeholder="请输入代理商ID" />-->
          <el-select
            v-model="form.platformAgentId"
            placeholder="代理商名称"
            clearable
            @change="getAllStation"
            size="small">
            <el-option
              v-for="area in agentList"
              :key="area.id"
              :label="area.agentName"
              :value="area.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="场站" prop="chargeStationId">
          <!--          <el-input v-model="form.chargeStationId" placeholder="请输入场站ID" />-->

          <el-select v-model="form.chargeStationId" placeholder="请选择场站" clearable>
            <el-option
              v-for="dict in stationList"
              :key="dict.id"
              :label="dict.stationName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分润类型" prop="shareType">
          <!--          <el-input v-model="form.platformAgentId" placeholder="请输入代理商ID" />-->
          <el-select
            v-model="form.shareType"
            placeholder="分润类型"
            clearable
            size="small">
            <el-option
              v-for="share in shareTypeList"
              :key="share.value"
              :label="share.label"
              :value="share.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="代理商分润比例" prop="shareRatio">
          <el-input
            type="number"
            style="width: 215px"
            min="1"
            max="100"
            placeholder="请输入代理商分润比例"
            v-model="form.shareRatio"
            @blur="handleBlur"
          >
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPlatformShare,
  getPlatformShare,
  delPlatformShare,
  addPlatformShare,
  updatePlatformShare
} from "@/api/business/platformShare";
import {getAllChargeStation, getAllStationByAgentId} from '@/api/business/station'
import {getAgentAll} from "@/api/platform/agent";

const shareTypeList = [
  /*{
    label: '利润分成',
    value: 'profit'
  }, */{
    label: '营业额分成',
    value: 'turnover'
  }
]
export default {
  name: "PlatformShare",
  data() {
    return {
      active: null,
      originalValue: '',
      shareTypeList,
      stationList:[],
      agentList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 代理商分账润规则表格数据
      platformShareList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        chargeStationId: null,
        lastUpdateTime: null,
        platformAgentId: null,
        shareRatio: null,
        shareType: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        chargeStationId: { required: true, message: '请选择场站' },
        platformAgentId: { required: true, message: '请选择代理商' },
        shareType: { required: true, message: '请选择分润类型' },
        shareRatio: { required: true, message: '请填写代理商分润比例'},
      }
    }
  },
  created() {
    this.getList();
    //this.getListStation()
    this.getAgentAll()
  },
  methods: {
    updateManager(row, key) {
      this.$confirm('是否确认此操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        row[key] === '1' ? row[key] = '0' : row[key] = '1'
        try {
          let res = await updatePlatformShare(row)
          this.$modal.msgSuccess(res.msg)
        } catch (e) {
          this.$modal.msgError(e)
        }
      }).catch(() => {
        this.$message.info('取消操作！')
      })
    },
    async getAllStation(val) {
      if (!val) {
        this.stationList = []
        this.form.chargeStationId = null
        return
      }
      let res = await getAllStationByAgentId(val)
      this.stationList = res.data
    },
    handleBlur() {
      if (this.form.shareRatio < 1 || this.form.shareRatio > 100) {
        this.form.shareRatio = 100
      }
    },
    getLabelByValue(entities, value) {
      for (let i = 0; i < entities.length; i++) {
        if (entities[i].value === value) {
          return entities[i].label
        }
      }
    },
    /** 查询场站列表 **/
    async getListStation() {
      let res = await getAllChargeStation()
      this.stationList = res.data;
    },
    async getAgentAll(){
      let res = await getAgentAll()
      this.agentList = res.rows
    },
    /** 查询代理商分账润规则列表 */
    getList() {
      this.loading = true;
      listPlatformShare(this.queryParams).then(response => {
        this.platformShareList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        chargeStationId: null,
        createBy: null,
        createTime: null,
        lastUpdateTime: null,
        platformAgentId: null,
        shareRatio: null,
        shareType: null,
        status: null,
        updateBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加代理商分账润规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPlatformShare(id).then(response => {
        this.form = response.data;
        this.getAllStation(this.form.platformAgentId)
        this.open = true;
        this.title = "修改代理商分账润规则";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePlatformShare(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlatformShare(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除代理商分账润规则编号为"' + ids + '"的数据项？').then(function() {
        return delPlatformShare(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/platformShare/export', {
        ...this.queryParams
      }, `platformShare_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-switch.is-disabled {
  opacity: 1;
}

::v-deep .el-switch.is-disabled .el-switch__core, .el-switch.is-disabled .el-switch__label {
  cursor: pointer !important;
}
</style>
